﻿using EMIS.Http;
using MQTTnet;
using MQTTnet.Client.Options;
using System;
using System.Threading;
using System.Windows;
using SmartShopping;
using System.IO.Ports;
using KV_WSN;

namespace EMIS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WinConfig : Window
    {
        public WinConfig()
        {
            InitializeComponent();
            var portNames = SerialPort.GetPortNames();
            // string[] ports;
            // cboxPortList.ItemsSource = portNames;
            if (portNames.Length > 0)
            {
                foreach (var portName in portNames)
                {
                    if (portName.Length < 7)
                    {
                        txtPort.Items.Add(portName);
                    }
                }
            }

            txtPort.SelectedIndex = 0;
        }

        private string _serverIp = "";
        private int _mqttPort;
        private int _apiPort;
        private int _gatewayId;

        private string _lightPortName = "";
        private string _fanName = "";
        private string _lockName = "";

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            // 获取所有的输入数据
            if (!CheckInput())
            {
                return;
            }

            // 连接mqtt服务器(连接结果无法判断)
            MainClass.MqttClient = new MqttFactory().CreateMqttClient();
            MqttClientOptions options = new MqttClientOptions();
            options.ChannelOptions = new MqttClientTcpOptions {Server = _serverIp, Port = _mqttPort};
            MainClass.MqttClient.ConnectAsync(options, CancellationToken.None);

            // 连接api接口
            var result = HttpHelper.Get($"http://{_serverIp}:{_apiPort}/", HttpHelper.HttpTestApi);
            if (result.Code == ResponseCode.Success)
            {
                // 判断mqtt连接状态
                if (MainClass.MqttClient.IsConnected)
                {
                    if (!Global.OpenPortZigbee(txtPort.Text))
                    {
                        _ = MessageBox.Show("串口打开失败");
                    }

                    Global.coordinator.Ping();
                    
                    DialogResult = true;
                    return;
                }

                MessageBox.Show($"MQTT服务器连接失败");
            }
            else
            {
                MessageBox.Show($"api服务器连接失败");
            }


            DialogResult = false;
        }

        /// <summary>
        /// 进行检查
        /// </summary>
        /// <returns></returns>
        public bool CheckInput()
        {
            _lightPortName = txtLightPortName.Text;
            if (string.IsNullOrEmpty(_lightPortName))
            {
                MessageBox.Show("射灯点名称不能为空");
                return false;
            }

            MainClass.LightPortName = _lightPortName;

            _fanName = txtFanName.Text;
            if (string.IsNullOrEmpty(_fanName))
            {
                MessageBox.Show("风扇点名称不能为空");
                return false;
            }

            MainClass.FanName = _fanName;

            _lockName = txtLockName.Text;
            if (string.IsNullOrEmpty(_lockName))
            {
                MessageBox.Show("锁点名称不能为空");
                return false;
            }

            MainClass.LockName = _lockName;

            string ip = txtIp.Text;
            if (string.IsNullOrEmpty(ip))
            {
                MessageBox.Show("服务器地址不能为空");
                return false;
            }

            _serverIp = ip;
            MainClass.ServerIp = _serverIp;

            try
            {
                int mqttPort = Convert.ToInt32(txtMqttPort.Text);
                _mqttPort = mqttPort;
                MainClass.MqttPort = _mqttPort;
            }
            catch (Exception e)
            {
                MessageBox.Show("MQTT服务器端口填写有误");
                return false;
            }

            try
            {
                int apiPort = Convert.ToInt32(txtApiPort.Text);
                _apiPort = apiPort;
                MainClass.ApiPort = _apiPort;
            }
            catch (Exception)
            {
                MessageBox.Show("API服务器端口填写有误");
                return false;
            }

            try
            {
                _gatewayId = Convert.ToInt32(txtDeviceId.Text);
                MainClass.GatewayId = _gatewayId;
            }
            catch (Exception)
            {
                MessageBox.Show("设备Id填写有误");
                return false;
            }

            return true;
        }
    }
}